// @flow
import React, { Component } from 'react'
import { message, Spin } from 'antd'
import moment from 'moment'
import { AgGridReact } from 'ag-grid-react'
import ServerListActions from './ServerListActions'
import { TableResize } from 'ag-grid-addons'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { connect } from 'react-redux'
import Pagination from 'components/Pagination'
import styles from './ServerListGrid.css'
import WarningFilter from 'components/WarningFilter'
import showTitle from './showTitle'
type Props = {
  pageSize: number,
  refreshServerList: Function,
  history: Object,
  deviceNo: any
}
type States = {
  count: number,
  total: number,
  current: number,
  columnDefs: Array<Object>,
  faultList: Array<Object>,
  loading: boolean
}
class ServerListGrid extends Component {
  props: Props
  state: States
  queryUrl: String
  gridOptions: Object
  onGridReady: Function
  TableResize: Function
  ignoreMeg: Function
  order: Function
  getTasks: Function
  handleSearch: Function
  api: Object
  constructor (props: Props) {
    super(props)
    this.onGridReady = this.onGridReady.bind(this)
    this.TableResize = TableResize.bind(this)
    this.ignoreMeg = this.ignoreMeg.bind(this)
    this.order = this.order.bind(this)
    this.getTasks = this.getTasks.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.state = {
      count: 0,
      total: 1,
      current: 1,
      loading: false,
      columnDefs:[
        // { headerName: '名称',
        //   field: 'faultName',
        //   width: 100,
        //   suppressSizeToFit: true,
        //   suppressMenu: true,
        //   cellStyle: {
        //     'padding': '8px'
        //   },
        //   cellRenderer: (params) => {
        //     const model = params.data.model
        //     if (model == null) {
        //       return ''
        //     } else {
        //       return model.name
        //     }
        //   }
        // },
        { headerName: '预警类型',
          field: 'type',
          width: 80,
          suppressSizeToFit: true,
          suppressMenu: true,
          cellRenderer: (params) => {
            const type = params.data.type
            if (type === 'real') {
              return '实时告警'
            } else {
              return '模型预警'
            }
          },
          cellStyle: {
            'padding': '8px'
          }
        },
        { headerName: '预警级别',
          field: 'level',
          width: 80,
          suppressSizeToFit: true,
          suppressMenu: true,
          cellStyle: {
            'padding': '8px'
          }
        },
        { headerName: '预警时间',
          field: 'waringTime',
          width: 140,
          suppressSizeToFit: true,
          suppressMenu: true,
          // cellRenderer: (params) => {
          //   return moment.utc(params.data.waringTime).format('YYYY-MM-DD HH:mm:ss')
          // },
          cellStyle: {
            'padding': '8px',
            'text-align':'center'
          }
        },
        { headerName: '处理状态',
          field: 'dealType',
          width: 80,
          suppressSizeToFit: true,
          suppressMenu: true,
          cellStyle: {
            'padding': '8px'
          },
          cellRenderer: (params) => {
            if (params.data.dealType === 0) {
              return '站内消息'
            } else if (params.data.dealType === 1) {
              return '已忽略'
            } else if (params.data.dealType === 2) {
              return '已生成工单'
            } else if (params.data.dealType === 3) {
              return '不显示'
            } else if (params.data.dealType === 4) {
              return '已短信通知'
            } else if (params.data.dealType === 5) {
              return '已邮件通知'
            } else if (params.data.dealType === 1) {
              return '重复数据,不处理'
            }
          }
        },
        { headerName: '操作',
          field: '',
          width: 220,
          suppressSizeToFit: true,
          suppressMenu: true,
          cellRendererParams: {
            history: this.props.history,
            refreshServerList: this.getTasks,
            ignoreMeg: this.ignoreMeg,
            order: this.order,
            getTasks: this.getTasks
          },
          cellRendererFramework: ServerListActions,
          cellStyle: {
            'padding': '8px',
            'text-align':'center'
          }
        },
        { headerName: '描述',
          field: 'message',
          width: 250,
          suppressMenu: true,
          cellStyle: {
            'padding': '8px',
            'text-align':'left'
          },
          cellRendererFramework: showTitle
        }
      ],
      faultList: []
    }
    this.gridOptions = {
      localeText: {
        loadingOoo: '数据加载中...',
        noRowsToShow: '暂无数据',
        filterOoo: '搜索当前页面',
        equals: '等于',
        notEqual: '不等于',
        contains: '包含',
        startsWith: '开始于',
        endsWith: '结束于',
        copy: '复制',
        paste: '粘贴',
        copyWithHeaders: '带表头复制',
        toolPanel: '工具栏',
        export: '导出',
        csvExport: '导出CSV',
        excelExport: '导出Excel'
      },
      enableSorting: true,
      enableFilter: true,
      rowSelection: 'single',
      rowDeselection: true,
      enableColResize: true
    }
  }

  onGridReady (params: Object) {
    this.api = params.api
    this.api.sizeColumnsToFit()
    this.TableResize()
  }
  componentDidMount () {
    const { pageSize } = this.props
    const { current } = this.state
    this.getTasks(current, pageSize)
  }
  handleSearch (searchQuery) {
    this.queryUrl = searchQuery
    this.getTasks(1, 20)
  }
  getTasks (page: number, pageSize: number) {
    let queryUrl = this.queryUrl || ``
    this.setState({
      loading: true
    })
    const { deviceNo } = this.props
    universalFetch(`${__SERVICE_API__}analysis/warings?deviceNo=${deviceNo}&pageNum=${page}&pageSize=${pageSize}${queryUrl}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          loading: false,
          current: page,
          total: json.pageInfo.total,
          faultList: json.result.map((d, i) => {
            d['waringTime'] = moment.utc(d.waringTime).format('YYYY-MM-DD HH:mm:ss')
            return d
          })
        })
      })
      .catch((error) => {
        this.setState({
          loading: false,
          faultList: []
        })
        handleFetchError(error)
        console.error(error)
      })
  }
  ignoreMeg (data) {
    const component = this
    const values = {
      'type': 'ignore'
    }
    universalFetch(`${__SERVICE_API__}analysis/warings/` + data.id,
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/jsoncharset=utf-8'
        },
        body: JSON.stringify(values)
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        // location.reload(true)
        const { pageSize } = component.props
        const { current } = component.state
        this.getTasks(current, pageSize)
        message.success('忽略成功')
      })
      .catch((error) => {
        message.success('忽略失败')
        handleFetchError(error)
        console.error(error)
      })
  }
  order (data) {
    const component = this
    universalFetch(`${__SERVICE_API__}analysis/warings/` + data.id + '?type=order',
      {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        // location.reload(true)
        const { pageSize } = component.props
        const { current } = component.state
        this.getTasks(current, pageSize)
        message.success('工单生成成功')
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        message.error('工单生成失败')
      })
  }
  render () {
    const { columnDefs, faultList, current, total, loading } = this.state
    const { pageSize } = this.props
    return (
      <div className={styles['serverGrid']}>
        <div className={styles['action']}>
          {/* <Button type='primary' onClick={this.addFault} style={{ marginTop: '6px' }}>添加故障记录</Button> */}
          <div style={{ paddingBottom: 5, paddingLeft: 12 }}>
            <WarningFilter getData={this.handleSearch} />
          </div>
        </div>
        <div className={styles['serverCon'] + ' ag-fresh'}>
          <Spin spinning={loading} className={styles['spanBg']} />
          <AgGridReact
            gridOptions={this.gridOptions}
            rowHeight='34'
            headerHeight='28'
            columnDefs={columnDefs}
            rowData={faultList}
            onGridReady={this.onGridReady}
          />
        </div>
        <Pagination current={current} pageSize={pageSize} total={total} onChange={this.getTasks} />
      </div>
    )
  }
}
const mapStatesToProps = (state) => {
  return {
    deviceNo: state.deviceCard.deviceData.deviceNo
  }
}
export default connect(mapStatesToProps, {})(ServerListGrid)
